﻿using FluentValidation.Results;
using JSONDB.Model;
using JSONDB.Validation;
using JsonFlatFileDataStore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace JSONDB.helpers
{
    
    public class JsonDBHelper
    {
        private string path  ;
        
        private DataStore store;

        IDocumentCollection<Item> collection  ;

        public JsonDBHelper(string path) {
            this.path = path;
            this.store = new DataStore(path);
            this.collection = store.GetCollection<Item>("config");
        }

        public void Save(Item item, out ValidationResult result)
        {
            ItemValidator validations = new ItemValidator();
            result = validations.Validate(item);
            if (result.IsValid) { collection.InsertOne(item); }
        }

        public List<Item> GetItems(string opcName, int pageSize, int pageNum , out int total) {
            List<Item> result = new List<Item>();
 
            if (opcName ==null || opcName.Trim().Length == 0)
            {
                total = collection.AsQueryable().Count();
                return collection.AsQueryable().Skip(pageSize * (pageNum - 1)).Take(pageSize).ToList();
            }
            total = collection.AsQueryable().Where(w => w.opcname.Equals(opcName)).Count();
            result = collection.AsQueryable().Where(w => w.opcname.Equals(opcName)).Skip(pageSize * (pageNum - 1)).Take(pageSize).ToList();
           
            return collection.AsQueryable().Where(w => w.opcname.Equals(opcName)).Skip(pageSize * (pageNum - 1)).Take(pageSize).ToList();
        }

        public List<Item> GetItems()
        {
            return  collection.AsQueryable().ToList();
        }

        public async Task UpdateFileCheckSum(string md5)
        {
            bool isSucessful = await store.UpdateItemAsync("checksum", md5);
            if (!isSucessful)
            {
                await store.InsertItemAsync("checksum", md5);
            }
        }

        public string GetFileCheckSum()
        {
            return store.GetItem(Constant.JSONFIELD_CHECKSUM_NAME);
        }

        public async Task ConfigSaveOrUpdate(Tag item)
        {
            var collection = store.GetCollection<Tag>("config");
            bool isSucessful = await collection.UpdateOneAsync((Predicate<Tag>)(t => t.name.Equals(item.name.Trim())), item);
            if (!isSucessful)
            {
                await collection.InsertOneAsync(item);
            }
        }
    }
}
